import {
  request
} from '../../utils/requestUtils';
import { userBehavior } from '../../behaviors/userBehavior'

Page({
  behaviors: [userBehavior],
  // 页面的初始数据
  data: {
    source:'',
    addressList: [],
    total: 0,
    page: {
      pageNum: 1,
      pageSize: 100,
    },
    params: {
      keywords: ''
    },
  },

  onLoad(option){
    if(option.source){
      // 如果是支付页面新增地址跳转过来的则需要把最新的地址返回去
      this.setData({
        source:option.source
      })
    }
  },
  onShow(option) {
    this.getPageList();
  },
  // 返回到支付页面
  goPay(event){
    if(!this.data.source || this.data.source != 'pay')return
    const {info} = event.currentTarget.dataset
    this.setDefaultAddr(info)
    wx.navigateBack({
      delta: 1
    })
  },
  // 去编辑页面
  toEdit(event) {
    const {id} = event.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/customer_addrss_add/index?id='+id
    })
  },
  // 删除地址
  async toDelete(event) {
    const modalRes = await wx.showModal({
      content: '您确认删除该收货地址吗 ?'
    })
    if (modalRes.cancel) return
    const {id} = event.currentTarget.dataset
    const result = await request({
      url: `/bus/customer/addr/${id}`,
      method: "DELETE"
    })
    if (result.data.code == 200) {
      this.getPageList()
    }
  },
  // 获取收货地址
  async getPageList() {
    const result = await request({
      url: `/bus/customer/addr/list?pageNum=${this.data.page.pageNum}&pageSize=${this.data.page.pageSize}`,
      method: "POST",
      data: {
        name: this.data.params.keywords,
        params: {
          keywords: ''
        }
      }
    })
    console.log('result.data', result.data)
    if (result.data.code == 200) {
      this.setData({
        addressList: result.data.rows
      })
    }
  }
})